package com.yjx.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Value("${loginPath}")
    private String loginPath;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取header的 source-type timestamp token
        HttpHeaders header=exchange.getRequest().getHeaders();
        String sourceType = header.getFirst("source-type");
        String timestamp = header.getFirst("timestamp");
        String token =header.getFirst("token");

        if (null == sourceType || sourceType.isEmpty()) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        if (null == timestamp || timestamp.isEmpty()) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //判断请求来源（login）
        String path = exchange.getRequest().getPath().toString();
        System.out.println(path);
        if (!loginPath.equals(path)) {
            if (null == token || token.isEmpty()) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        }

        //判断是否为空
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
